<?php

/**
 * 后台公共文件 
 * @file   Common.php  
 * @date   2016-8-24 18:28:34 
 * @author Zhenxun Du<5552123@qq.com>  
 * @version    SVN:$Id:$ 
 */

namespace app\api\controller;

use think\Controller;
use rongcloud\RongCloud;
use \OSS\OssClient;

class Common extends Controller {
    protected $inData,$outData,$rong_cloud,$db_app;


    public function __construct(\think\Request $request = null) {

        parent::__construct($request);
        header('Access-Control-Allow-Origin','*');
        $this->outData = array('data'=>'','code'=>'','message'=>'');//输出参数

        include VENDOR_PATH.'rongcloud/RongCloud.php';
        // 获取key和secret
        $key_secret=get_rong_key_secret();
        // 实例化融云
        $this->rong_cloud = new RongCloud($key_secret['key'],$key_secret['secret']);


    }

    /**
     * 发送融云系统消息
     * @param $targetRongId 目标rongid
     * @param $content 系统消息内容
     * @param $pushContent = "系统消息" 推送内容
     * @return array
     */
    public function sendSysMsg($targetRongId,$content,$pushContent = "系统消息") {
        $contentJson['content'] = $content;
        $contentJson = json_encode($contentJson);

        $pushDataJson['pushData'] = $pushContent;
        $pushDataJson = json_encode($pushDataJson);
        // 发送系统消息
        $result_array = $this->rong_cloud->message()->PublishSystem('1', $targetRongId, 'RC:TxtMsg',$contentJson, $pushContent, $pushDataJson, '0', '0');
        $result_array = json_decode($result_array, true);
        return $result_array;
    }

    /**
     * @param $savePath
     * @param string $category
     * @param bool $isunlink
     * @param string $bucket
     * @return string
     */
    function aliyun($savePath,$category='',$isunlink=false,$bucket="dddgame"){
        $accessKeyId = config('aliyun_oss.accessKeyId');//去阿里云后台获取秘钥
        $accessKeySecret = config('aliyun_oss.accessKeySecret');//去阿里云后台获取秘钥
        $endpoint = config('aliyun_oss.endpoint');//你的阿里云OSS地址
        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
        //        判断bucketname是否存在，不存在就去创建
        if( !$ossClient->doesBucketExist($bucket)){
            $ossClient->createBucket($bucket);
        }
        $category=empty($category)?$bucket:$category;

        $savePath = str_replace("\\","/",$savePath);

        $object = $category.'/'.$savePath;//想要保存文件的名称
        $file = './uploads\\'.$savePath;//文件路径，必须是本地的。

        try{
            $ossClient->uploadFile($bucket,$object,$file);
            if ($isunlink==true){
                unlink($file);
            }
        }catch (OssException $e){
            $e->getErrorMessage();
        }
        $oss=config('aliyun_oss.url');
        return $oss."/".$object;
    }
}
